package com.dengpp.pdform.holder;

import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;

import com.dengpp.pdform.R;
import com.dengpp.pdform.adapter.AttributeAdapter;
import com.dengpp.pdform.api.CustomFormView;
import com.dengpp.pdform.base.BaseAttributeViewHolder;
import com.dengpp.pdform.config.AttributeConfig;

/**
 * 创建自定义视图 Holder
 */

public class CustomViewHolder extends BaseAttributeViewHolder {
    private TextView tvTitle;
    private ViewGroup customContainer;
    private CustomFormView customFormView;
    private AttributeConfig currentAttribute;

    public CustomViewHolder(@NonNull View itemView) {
        super(itemView);
        tvTitle = itemView.findViewById(R.id.tv_title);
        customContainer = itemView.findViewById(R.id.custom_container);
    }

    @Override
    public void bind(AttributeConfig attribute, boolean isEditMode, AttributeAdapter.OnAttributeChangeListener listener) {
        this.currentAttribute = attribute;

        // 使用带星号的标题
        tvTitle.setText(getTitleWithRequiredStar(attribute.getTitle(), attribute.isRequired()));

        try {
            // 创建自定义视图实例
            if (customFormView == null && attribute.getCustomViewClass() != null) {
                customFormView = (CustomFormView) attribute.getCustomViewClass().newInstance();
                View customView = customFormView.createView(itemView.getContext());

                // 清除容器并添加自定义视图
                customContainer.removeAllViews();
                customContainer.addView(customView);

                // 设置值变化监听
                customFormView.setOnValueChangeListener(value -> {
                    if (listener != null && currentAttribute == attribute) {
                        listener.onAttributeChanged(attribute.getKey(), value);
                    }
                });

                attribute.setCustomViewInstance(customView);
            }

            // 绑定数据
            if (customFormView != null) {
                customFormView.bindData(attribute, attribute.getValue());
            }

        } catch (Exception e) {
            e.printStackTrace();
            Log.e("CustomViewHolder", "创建自定义视图失败", e);
        }
    }

    @Override
    public void onViewRecycled() {
        super.onViewRecycled();
        // 清理资源
        if (customFormView != null) {
            customFormView.setOnValueChangeListener(null);
            customFormView.onDestroy();
        }
        customFormView = null;
        currentAttribute = null;

        // 清空容器内容
        if (customContainer != null) {
            customContainer.removeAllViews();
        }
    }
}
